/**
 * COPYRIGHT. Harry Wu 2011. ALL RIGHTS RESERVED.
 * Project: wenda-component
 * Author: Harry Wu <harrywu304@gmail.com>
 * Created On: Jul 6, 2011 6:47:42 PM
 *
*/ 
package just.sample.wenda.res;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import just.sample.wenda.model.Topic;

import org.justframework.api.connector.Request;
import org.justframework.api.connector.Response;

/**
 * topic resource 
 * topic instance has field id, subject and content
 * default value is id<num> subject<num> content<num>
 * initial fill instance from 0 to 99
 *
 */
public class TopicResource {
	
	private static Map<String, Topic> topics;
	
	static {
		topics = new ConcurrentHashMap<String,Topic>();
		//fill initial topics
		for(int i=0;i<100;i++){
			Topic topic = new Topic();
			topic.setTopicId("id"+i);
			topic.setSubject("subject"+i);
			topic.setContent("content"+i);
			topics.put(topic.getTopicId(),topic);
		}
	}
	
	//get topic return topic instance
	public void get(Request request, Response response){
		String topicId = (String)request.getParam("topicId");
		Topic topic = topics.get(topicId);
		response.setContent(topic);
	}
	
	//create topic return topic id
	public void post(Request request, Response response){
		String subject = request.getParam("subject");
		String content = request.getParam("content");
		Topic topic = new Topic();
		String topicId = UUID.randomUUID().toString();
		topic.setTopicId(topicId);
		topic.setSubject(subject);
		topic.setContent(content);
		topics.put(topicId, topic);
		response.setContent(topicId);
	}
	
	//update topic content return true
	public void put(Request request, Response response){
		String topicId = (String)request.getParam("topicId");
		String content = (String)request.getParam("content");
		Topic topic = topics.get(topicId);
		if(topic != null){
			topic.setContent(content);
		}
		response.setContent(true);
	}
	
	//delete topic return true
	public void delete(Request request, Response response){
		String topicId = (String)request.getParam("topicId");
		topics.remove(topicId);
		response.setContent(true);
	}

}
